import { playPrev, playNext, playEnded } from './play-list';
import { LOGIN_STATUS, EVENT_BUS_KEY } from '../../common/constants';
import { formatSecond } from '../../utils/date';
import { eventBusGetter } from '../../utils/eventbus';
import { navigateTo } from '../../common/service/page-service';
import { getLoginStatus } from '../../common/service/user-service';
import { setCurrentLesson, getCurrentLesson, setStudiedLesson, removeCurrentLesson, lessonToAudio } from '../../common/service/courses-service';

/** 用事件通知父组件，开始播放 */
const EVENT_PLAY_START = 'playStart';
/** 用事件通知父组件，暂停播放 */
const EVENT_PLAY_PAUSE = 'playPause';
/** 用事件通知父组件，正在播放 */
const EVENT_PLAY_TIME_UPDATE = 'playTimeUpdate';
/** 用事件通知父组件，播放上一首 */
const EVENT_PLAY_PREV = 'playPrev';
/** 用事件通知父组件，播放下一首 */
const EVENT_PLAY_NEXT = 'playNext';
/** 用事件通知父组件，播放结束 */
const EVENT_PLAY_ENDED = 'playEnded';
/** 微信后台播放器必须设置的字段名 */
const AUDIO_KEYS = ['src', 'title', 'singer', 'coverImgUrl'];
/** 快进/快退播放的步长。单位：秒 */
const SEEK_STEP = 15;

Component({
    properties: {
        audioInfo: {
            type: Object,
            value: {},
            observer: function (newVal, oldVal) {
                this.initAudio(false);
            }
        },
        skinMode: { // 播放器显示模式。1:全功能独立页面；2:悬浮状态
            type: String,
            value: '2'
        },
        refreshStatus: {
            type: Number,
            value: 0,
            observer: function (newVal, oldVal) {
                this.initAudio(newVal !== oldVal);
            }
        },
        disablePrev: { // 是否禁用上一首按钮
            type: Boolean,
            value: false
        },
        disableNext: { // 是否禁用下一首按钮
            type: Boolean,
            value: false
        },
        isRise: { // 浮动状态时，是否上浮一定区域
            type: Boolean,
            value: false
        },
        isFinish: { // 播放完最后一节，通知播放器
            type: Number,
            value: 0,
            observer: function (newVal, oldVal) {
                console.log('_playFinish:', newVal);
                this._playFinish();
            }
        }
    },
    data: {
        isInit: false, // 组件是否已经初始化
        isShow: false, // 是否显示播放器
        isRefreshProcess: true, // 是否更新进度条
        status: 0, // 播放状态。0:暂停；1:正在播放；2:停止：3:没有可播放的数据
        objAudio: {},
        // currentAudioId: 0,
        // currentProcess: 0,
        audioTitle: '',
        processPercent: 0, // 当前的播放进度的100比
        totalProcess: 0, // 音频的总时长，单位：秒
        strCurrentProcess: '00:00', // 易读的，当前的播放时间
        strTotalProcess: '--:--' // 易读的，音频总时长
    },
    created: function (params) {
        eventBusGetter().$on(EVENT_BUS_KEY.PLAY_UPDATE_STATUS, () => {
            // console.log('进入小程序收到更新播放器的通知   pause', wx.getBackgroundAudioManager().paused);
            this._updateAudioStatus(getCurrentLesson({ isSync: true }));
        });
    },
    methods: {
        _playFinish: function () {
            // this._updateCurrentLesson({
            //     status: 3
            // });
            // this.setData({
            //     status: 3,
            //     processPercent: 0,
            //     strCurrentProcess: '00:00'
            // });
            this._resetAudioUI();
        },
        _updateCurrentLesson: function (params) {
            if (!params) {
                return;
            }

            // let _data = this.data;
            let updateKey = ['currentProcess', 'totalProcess', 'status', 'isInit'];
            let updateData = {};

            updateKey.forEach(key => {
                if (typeof params[key] !== 'undefined') {
                    updateData[key] = params[key];
                }
            });

            let currentLesson = getCurrentLesson({ isSync: true });
            if (currentLesson) {
                setCurrentLesson(Object.assign({}, currentLesson, updateData));
            };
        },
        _getCurrentAudioStatus: function (currentLesson) {
            // let currentLesson = lessonToAudio(getCurrentLesson({ isSync: true }));
            if (currentLesson === undefined) {
                return;
            }
            let isShow = true;
            if (this.data.skinMode === '2' && currentLesson.status === 2) {
                isShow = false;
            }
            let obj = {
                isShow,
                objAudio: currentLesson,
                processPercent: this._computeProcess(currentLesson.currentProcess),
                audioTitle: currentLesson.title,
                status: currentLesson.status,
                strCurrentProcess: formatSecond(currentLesson.currentProcess),
                strTotalProcess: formatSecond(currentLesson.totalProcess)
            };

            // console.log(JSON.stringify('_getCurrentAudioStatus:', obj));
            return obj;
        },
        /** 算播放进度百分比 */
        _computeProcess: function (currentProcess) {
            // let _data = this.data;
            let currentLesson = getCurrentLesson({ isSync: true });
            if (typeof currentProcess === 'undefined') {
                return;
            }
            return (currentProcess / currentLesson.totalProcess) * 100;
        },
        /** 重置播放器的数据，让播放器重新播放 */
        _resetAudioData: function (audio) {
            // 初始化后台播放组件环境
            this.objAudio.startTime = 0;
            for (let key in audio) {
                if (audio.hasOwnProperty(key) && AUDIO_KEYS.indexOf(key) >= 0) {
                    this.objAudio[key] = audio[key];
                }
            }

            removeCurrentLesson({ isSync: true });
            // 当前缓存中没有课程，需要重新初始化播放器
            // setCurrentLesson(Object.assign({}, audio));
            // setStudiedLesson(Object.assign({}, audio));
            setCurrentLesson(JSON.parse(JSON.stringify(audio)));
            setStudiedLesson(JSON.parse(JSON.stringify(audio)));
        },
        /** 更新播放器的状态 */
        _updateAudioStatus: function (currentLesson) {
            let obj = this._getCurrentAudioStatus(currentLesson);
            // console.log(obj);
            obj && this.setData(obj);
        },
        /** 更新播放器UI */
        _resetAudioUI: function () {
            console.log('_resetAudioUI');
            let _data = this.data;
            let data = {};
            if (_data.skinMode === '2') {
                data.isShow = false;
                data.status = 2;
            }
            data && this.setData(data);

            this._updateCurrentLesson({
                currentProcess: 0,
                status: 2
            });
        },
        initAudio: function (isRefreshStatus) {
            console.log('============initAudio:', this.properties.skinMode);
            let _props = this.properties;
            let _data = this.data;
            let audioInfo = lessonToAudio(_props.audioInfo);
            let currentLesson = lessonToAudio(getCurrentLesson({ isSync: true }));
            // 没有正在学习的课程，同时没有传递播放对象
            if (!currentLesson && typeof audioInfo === 'undefined') {
                this.setData({
                    isShow: false
                });
                return;
            }

            this.objAudio = wx.getBackgroundAudioManager();
            this.initEvent();

            if (typeof audioInfo === 'undefined' || (isRefreshStatus && currentLesson)) {
                // 当前缓存中已经有课程，证明已经有开始播放的音频
                // 不需要重新初始化播放器，直接更新状态即可
                console.log(this._getCurrentAudioStatus(currentLesson));
                this.setData(this._getCurrentAudioStatus(currentLesson));
            } else if (audioInfo && currentLesson && (audioInfo.lessonId === currentLesson.lessonId)) {
                this.setData(this._getCurrentAudioStatus(currentLesson));
            } else {
                this.setData({
                    isInit: true,
                    isShow: true,
                    // currentProcess: 0,
                    processPercent: 0,
                    totalProcess: 0
                });

                this._resetAudioData(audioInfo);
            }
        },
        initEvent: function () {
            this.objAudio.onEnded(() => {
                console.log('onEnded');
                let lesson = getCurrentLesson({isSync: true});
                if (playEnded(lesson.lessonId)) {

                }
                // 播放结束
                // let _props = this.properties;
                this.setData({
                    isInit: false,
                    status: 0
                });
                // this.triggerEvent(EVENT_PLAY_ENDED, {
                //     currentAudio: lesson
                // });
            });

            this.objAudio.onPlay(() => {
                console.log('onPlay');
                this._updateCurrentLesson({
                    status: 1
                });
                this.setData({
                    isInit: true,
                    status: 1
                });
            });

            this.objAudio.onCanplay(() => {
                console.log('onCanplay');
                this._updateCurrentLesson({
                    status: 1
                });
            });

            this.objAudio.onStop((e) => {
                console.log('onStop:', JSON.stringify(e));
                this._resetAudioUI();
                eventBusGetter().$emit(EVENT_BUS_KEY.PLAYER_STAT_STOPPED, {});
            });

            this.objAudio.onPause(() => {
                console.log('onPause');
                let _props = this.properties;
                this._updateCurrentLesson({
                    status: 0
                });
                this.triggerEvent(EVENT_PLAY_PAUSE, {
                    currentAudio: _props.audioInfo
                });
                this.setData({
                    status: 0
                });
            });

            this.objAudio.onWaiting(() => {
                console.log('onWaiting');
            });

            this.objAudio.onPrev(() => {
                let _props = this.properties;
                this.triggerEvent(EVENT_PLAY_PREV, {
                    currentAudio: _props.audioInfo
                });
            });

            this.objAudio.onNext(() => {
                let _props = this.properties;
                this.triggerEvent(EVENT_PLAY_NEXT, {
                    currentAudio: _props.audioInfo
                });
            });

            this.objAudio.onError(function (e) {
                console.error('onError:', e);
            });

            // 更新播放进度
            this.objAudio.onTimeUpdate(() => {
                let _data = this.data;
                let _props = this.properties;
                let currentProcess = this.objAudio.currentTime;
                let totalProcess = this.objAudio.duration;
                // 全局变量修改当前播放进度，方面跨页面更新播放器状态
                this._updateCurrentLesson({
                    currentProcess: currentProcess,
                    totalProcess
                });

                this.triggerEvent(EVENT_PLAY_TIME_UPDATE, {
                    currentAudio: _props.audioInfo,
                    currentTime: currentProcess
                });

                try {
                    let data = {
                        strCurrentProcess: formatSecond(currentProcess),
                        strTotalProcess: formatSecond(this.objAudio.duration)
                    };

                    if (_data.isRefreshProcess) {
                        data.processPercent = this._computeProcess(currentProcess);
                    }
                    this.setData(data);
                } catch (error) {

                }
            });

            // 监听用户登录状态更新，如果用户登录状态变化，清理环境，重置播放器
            eventBusGetter().$on(EVENT_BUS_KEY.LOGIN_STATUS_UPDATE, () => {
                if (getLoginStatus() === LOGIN_STATUS.ZH_LOGIN_SUCCESS || getLoginStatus() === LOGIN_STATUS.ZH_LOGIN_FAILED) {
                    this.handleAudioStop();
                }
            });
        },
        // 更新进度条状态
        setCurrentProcess: function (e) {
            let value = e.detail.value;
            if (typeof value !== 'undefined') {
                let curPlayTime = Math.floor(this.objAudio.duration * (value / 100));
                this.objAudio.seek(curPlayTime);

                this._updateCurrentLesson({
                    currentProcess: curPlayTime
                });
                this.setData({
                    strCurrentProcess: formatSecond(curPlayTime),
                    isRefreshProcess: true
                });
            }
        },
        // 停止刷新进度条
        stopRefreshProcess: function () {
            this.setData({
                isRefreshProcess: false
            });
        },
        // 播放控制。 开放播放；暂停播放
        handlePlayControl: function () {
            console.log('handlePlayControl');
            let _data = this.data;

            if (_data.status === 0) {
                // 暂停
                this.objAudio.play();
                this._updateCurrentLesson({
                    currentProcess: this.objAudio.currentTime,
                    status: 1
                });
                this.setData({
                    status: 1,
                    isInit: true
                });
                eventBusGetter().$emit(EVENT_BUS_KEY.PLAYER_STAT_RESUMED, {});
            } else if (_data.status === 1) {
                // 正在播放
                this.objAudio.pause();
                this._updateCurrentLesson({
                    currentProcess: this.objAudio.currentTime,
                    status: 0
                });
                this.setData({
                    status: 0
                });
                eventBusGetter().$emit(EVENT_BUS_KEY.PLAYER_STAT_PAUSED, {});
            } else if (_data.status === 2) {
                // 外部停止播放，重新播放
                let objLesson = lessonToAudio(getCurrentLesson({ isSync: true }));
                if (_data.skinMode === '1') {
                    this.objAudio = wx.getBackgroundAudioManager();
                    this.initEvent();
                    this._resetAudioData(objLesson);
                }
            } else if (_data.status === 3) {
                // 没有可播放的音频
                let currentLesson = lessonToAudio(getCurrentLesson({ isSync: true }));
                this.objAudio.startTime = 0;
                for (let key in currentLesson) {
                    if (currentLesson.hasOwnProperty(key) && AUDIO_KEYS.indexOf(key) >= 0) {
                        this.objAudio[key] = currentLesson[key];
                    }
                }
                this._updateCurrentLesson({
                    status: 1
                });
            }
        },
        // 后退15秒
        handlePlayBack: function () {
            wx.seekBackgroundAudio({
                position: Math.floor(this.objAudio.currentTime - SEEK_STEP)
            });
        },
        // 前进15秒
        handlePlayForward: function () {
            wx.seekBackgroundAudio({
                position: Math.floor(this.objAudio.currentTime + SEEK_STEP)
            });
        },
        // 上一曲
        handlePlayPrv: function () {
            // let _props = this.properties;
            // this.triggerEvent(EVENT_PLAY_PREV, {
            //     currentAudio: _props.audioInfo
            // });
            if (this.data.skinMode !== '1') {
                return;
            }
            let lesson = getCurrentLesson({ isSync: true });
            if (playPrev(lesson.lessonId)) {

            } else {
                console.log('没有上一首');
            }
        },
        // 下一曲
        handlePlayNext: function () {
            console.log('=============', JSON.stringify(this.properties.skinMode));
            if (this.properties.skinMode !== '1') {
                return;
            }
            let lesson = getCurrentLesson({isSync: true});
            if (playNext(lesson.lessonId)) {

            } else {
                console.log('没有下一首');
            }
        },
        // 关闭播放器
        handleAudioStop: function (e) {
            if (this.objAudio) {
                this.objAudio.stop();
                this.setData({
                    isShow: false
                });
                removeCurrentLesson();
                eventBusGetter().$emit(EVENT_BUS_KEY.PLAYER_STAT_STOPPED, {});
            }
        },
        // 打开正在播放音频的听课页
        handleToListen: function (e) {
            if (this.objAudio) {
                let lesson = getCurrentLesson({ isSync: true });
                let { courseId, lessonId } = lesson;
                navigateTo({
                    url: `/pages/listen/listen?courseId=${courseId}&lessonId=${lessonId}`
                });
            }
        }
    }
});
